package com.sinosoft.brokerchannel.base.utile;


import com.sinosoft.brokerchannel.base.common.ChannelConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 功能：图片处理工具类<br/>
 * @author shilk
 * @date 2017-11-17 14:36:02
 */
public class ImageUtils {
    private final static Logger logger = LoggerFactory.getLogger(ImageUtils.class);
    /**
     * 功能：从网络Url中下载文件转为byte数组<br/>
     * 创建人：石李鲲<br/>
     * 创建时间：2017-11-17 14:40:42<br/>
     * @param urlStr-文件URL
     * @return 文件流数组
     */
    public byte[]  downLoadFromUrl(String urlStr) throws BusinessException {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3*1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            return readInputStream(inputStream);
        } catch (Exception e) {
            logger.error("downLoadFromUrl exception",e);
            throw new BusinessException(ChannelConstants.ExceptionResult.IMAGEDOWNERROE.getCode(),
                    ChannelConstants.ExceptionResult.IMAGEDOWNERROE.getMessage(),
                    e);
        }
    }

    /**
     * 功能：从输入流中获取字节数组<br/>
     * 创建人：石李鲲<br/>
     * 创建时间：2017-11-17 14:40:42<br/>
     * @param inputStream 文件流
     */
    private byte[] readInputStream(InputStream inputStream) throws BusinessException, IOException {
        ByteArrayOutputStream bos = null;
        try {
            byte[] buffer = new byte[1024];
            int len;
            bos = new ByteArrayOutputStream();
            while((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            logger.error("readInputStream exception",e);
            throw new BusinessException(ChannelConstants.ExceptionResult.IMAGEDOWNERROE.getCode(),
                    ChannelConstants.ExceptionResult.IMAGEDOWNERROE.getMessage(),
                     e);
        }finally {
            if(bos != null){
                bos.close();
            }
        }
    }

    /**
     * 功能：根据byte数组，生成文件
     * 创建人：shilk
     * 创建时间：2017-11-17 15:01:54
     */
    private static void getFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file;
        try {
            File dir = new File(filePath);
            //判断文件目录是否存在
            if(!dir.exists()&&dir.isDirectory()){
                boolean dirFlag = dir.mkdirs();
                if(!dirFlag){
                    logger.error("创建文件夹"+filePath+"失败");
                }
            }
            file = new File(filePath+"\\"+fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}
